const express = require('express');
const router = express.Router();
const db = require('../config/db');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { generateToken } = require('../utils/verifyToken'); //token验证

// 注册接口
router.post('/register', async (req, res) => {
  try {
    const { username, password, email } = req.body;
    
    // 检查用户是否已存在
    const [existing] = await db.query('SELECT * FROM users WHERE username = ?', [username]);
    if (existing.length > 0) {
      return res.status(400).json({ message: '用户名已存在' });
    }

    // 密码加密
    const hashedPassword = await bcrypt.hash(password, 10);
    
    // 插入新用户
    await db.query(
      'INSERT INTO users (username, password, email) VALUES (?, ?, ?)',
      [username, hashedPassword, email]
    );

    res.status(201).json({ message: '注册成功' });
  } catch (error) {
    res.status(500).json({ message: '注册失败', error });
  }
});

// 登录接口
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;
    
    // 查找用户
    const [users] = await db.query('SELECT * FROM users WHERE username = ?', [username]);
    if (users.length === 0) {
      return res.status(401).json({ message: '该用户未注册，请先注册' });
    }

    const user = users[0];
    
    // 验证密码
    const isValid = await bcrypt.compare(password, user.password);
    if (!isValid) {
      return res.status(401).json({ message: '密码错误' });
    }

    // 检查环境变量是否存在
    if (!process.env.JWT_SECRET) {
      throw new Error('JWT_SECRET is not defined');
    }

    // 生成 JWT token
    generateToken(0)
    const token = generateToken( { id: user.id, username: user.username });
    res.json({
      message: '登录成功',
      token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email
      }
    });
  } catch (error) {
    console.error('Login error:', error);
    res.status(500).json({ 
      message: '登录失败', 
      error: error.message || '未知错误'
    });
  }
});

// 重置密码接口
router.post('/reset-password', async (req, res) => {
  try {
    const { username, email, newPassword } = req.body;
    
    // 验证用户是否存在
    const [users] = await db.query('SELECT * FROM users WHERE username = ? AND email = ?', [username, email]);
    if (users.length === 0) {
      return res.status(400).json({ message: '用户名或邮箱不正确' });
    }

    const hashedPassword = await bcrypt.hash(newPassword, 10);
    
    // 更新用户密码
    await db.query('UPDATE users SET password = ? WHERE username = ?', [hashedPassword, username]);

    res.json({ message: '密码重置成功' });
  } catch (error) {
    res.status(500).json({ message: '密码重置失败', error });
  }
});

module.exports = router; 